<template>
  <div>
    <BreakSpace label="订单信息" :containerStyle="{ marginBottom: '10px' }"/>
    <!-- 新增、明细、编辑 -->
    <div>
      <FormPanel
        ref="formPanel"
        :list="formList"
        :cols="3"
        :formType="type"
        labelWidth="90"
        :isSubmitBtn="false"
        @formChange="formChangeHandle"
      />
    </div>
    <BreakSpace label="车辆信息" :containerStyle="{ marginBottom: '10px' }"/>
    <div>
      <FilterTable
	      ref="table"
        height="auto"
        :dataSource="dataSource"
	      :columns="columns"
        :onRowSelectChange="selectChange"
	      :onColumnsChange="columns => this.columns = columns"
	    >
        <template slot="controls">
          <el-button type="primary" v-if="type != 'show'" @click="addHendler">新增</el-button>
          <el-button :disabled="isChoice" type="primary" v-if="type != 'show'" @click="deleteHendler">删除</el-button>
        </template>
      </FilterTable>
    </div>
    <BreakSpace label="维护项目费用" :containerStyle="{ marginBottom: '10px' }"/>
    <div style="margin-top: 15px;">
      <FormPanel
        ref="formPanel2"
        :list="formList2"
        :cols="2"
        :formType="type"
        labelWidth="90"
        :isSubmitBtn="false"
        @formChange="formChangeHandle2"
      />
    </div>
    <div>
      <FilterTable
	      ref="tableA"
        height="auto"
        :dataSource="serviceSource"
	      :columns="columnsA"
        :onRowSelectChange="selectServiceChange"
	      :onColumnsChange="columnsA => this.columnsA = columnsA"
	    >
        <template slot="controls">
          <el-button :disabled="dataSource.length===0" type="primary" v-if="type != 'show'" @click="addServicePrograms">新增</el-button>
          <el-button :disabled="isServiceChoice" type="primary" v-if="type != 'show'" @click="deleteServicePrograms">删除</el-button>
        </template>
      </FilterTable>
    </div>
    <div style="margin-top: 15px;">
      <FormPanel
        ref="formPanel3"
        :list="formList3"
        :cols="2"
        :formType="type"
        labelWidth="90"
        :isSubmitBtn="false"
        @formChange="formChangeHandle3"
      />
    </div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'center'
      }"
    >
      <el-button v-if="type == 'show'" @click="closeDialog">返 回</el-button>
      <el-button v-if="type != 'show'" @click="closeDialog">取 消</el-button>
      <AjaxButton v-if="type != 'show'" :click="()=>saveDialog(10041001)">提 交</AjaxButton>
      <AjaxButton v-if="type != 'show'" :click="()=>saveDialog(10041002)" type="primary">保 存</AjaxButton>
    </div>

    <BaseDialog
      :visible.sync="visible"
      :title="dialogTitle"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <SearchName :type="handleType" :rowData="formData" @close="closeHandler" />
    </BaseDialog>

    <!-- 潜客选择 -->
    <BaseDialog
    	title="潜客选择"
    	:visible.sync="visible3"
    	destroyOnClose
    >
	    <clueSelection @close="closeDialogs" :consultantList="popUseConsultantList" @close2="closeDialogs2"></clueSelection>
    </BaseDialog>

    <!-- 新增产品选择 -->
    <!-- <BaseDialog
      :visible.sync="visible2"
      title="产品选择"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <productSelection :type="handleType" :modifyType="modifyType" :rowData="formData" @close="closeHandler22" @close2="closeHandler2" />
    </BaseDialog> -->
    <!-- 20191207单选变多选 -->
    <BaseDialog
      :visible.sync="visibleMultiple"
      title="产品选择"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <productSelectionMultiple :type="handleType" :modifyType="modifyType" :rowData="formData" @close="closeHandler22Multiple" @close2="closeHandler2Multiple" />
    </BaseDialog>

    <Drawer
      :visible.sync="visible4"
      title="销售订单编辑"
      :width="900"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <orderDetails :type="handleType" :baseData="formList" :rowData="formData" @close="closeHandler4" />
    </Drawer>
    <!-- 配车,拿到VIN -->
    <BaseDialog
      :visible.sync="visibleConfirmCar"
      title="VIN选择"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <ConfirmCar :rowData="formData" @close="closeConfirmCar" />
    </BaseDialog>
    <!-- 新增维护项目费用 -->
    <BaseDialog
      :visible.sync="visibleService"
      title="维护项目费用"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <serviceSelection @close="closeServiceDialog" />
    </BaseDialog>


  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { formatdate } from '@/utils/index';
import CancelDrive from './cancelDrive';
import SearchName from './searchName';
import moment from 'moment';
import { quyOrders, addOrders, modifyOrders } from '@/api/retail/salesmanage/salesordermanage';
import productSelection from './productSelection'
import productSelectionMultiple from './productSelectionMultiple'
import clueSelection from './clueSelection'
// import orderDetails from './orderDetails'
import orderDetails from '../salesorder/orderDetails'
import serviceSelection from './serviceSelection'
// import { getEmployeeList } from '@/utils/index';
import { getUsersByPosition } from '@/api/retail/salesmanage/salesordermanage';
import { getUserInfo } from '@/api/potenCus/customer/exhibition'
import ConfirmCar from '../confirmcar/clueSelection';
import { IDNumber, phone, email, formatDates, formatDat, checkPassport} from '@/utils/validate'

export default {
  name: 'DriveModal',
  mixins: [dictionary],
  components: {
    SearchName,
    productSelection,
    productSelectionMultiple,
    clueSelection,
    orderDetails,
    serviceSelection,
    ConfirmCar
  },
  props: {
    type: {
      type: String,
      default: 'add'
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    this.saveData = null;
    this.saveData2 = null;
    this.saveData3 = null;
    return {
      formList: this.createFormList(), //上方明细数据
      formList2: this.createFormList2(), //下方数据车辆总价
      formList3: this.createFormList3(), //下方数据服务总价
      columns: this.createTableColumns(), //table数据
      columnsA: this.createTableColumnsA(), // 服务项目table数据
      dataSource: [], //默认的赋值
      selectedRows: [], //选中列表中的行
      selectedServiceRows: [], // 服务项目列表中选中的行
      isChoice: true, //按钮是否可以选择
      isServiceChoice: true,
      handleType: '', //类型
      clueData: {}, //线索数据
      vehicleProductData: {},
      formData: {},
      visible: false,
      visible2: false,
      visible3: false,
      visible4: false,
      visibleMultiple:false,
      visibleService: false, // 服务项目dialog
      visibleConfirmCar: false, // 配车dialog
      dialogTitle: '',
      conf: { search: '选择试驾客户' },
      orderInfo: {}, // 订单详情
      recordId: '',
      EditConsultantId: '',
      modifyType: false,
      modifyIndex: null,
      popUseConsultantList: [],
      serviceSource: [] // 服务项目
    };
  },
  created () {
  },
  mounted () {
    this.init()
    getUserInfo().then(res => {
      let {userInfo} = res.data
      this.formList.find(item => item.fieldName === 'sheetCreatedBy').initialValue = userInfo.userName
    })
    this.employeeList();
  },
  methods: {
    updataNow(){
      console.log('this.$refs.table.GET_UPDATE_ROWS()',this.dataSource)
    },
    async employeeList() {
      let params = {
        positionCodes: [10061015],
        menuId: 223001
      }
      const res = await getUsersByPosition(params);
      // console.log('销售顾问', res)
      if (res.resultCode === 200) {
        let orginList = res.data.map(x => ({ value: x.userId, text: x.userName }));
        this.consultantList = orginList.filter((item,index,array) => {
          return array.findIndex(el=>el.value==item.value)===index
        })
        this.formList.find(item => item.fieldName === 'sheetCreatedBy').itemList = this.consultantList
        this.popUseConsultantList = this.consultantList
      }
    },
    init() {
      if (this.type === 'edit' || this.type === 'show') {
        // 更新接口需要的记录 ID
        this.recordId = this.rowData.soNoId;
        this.clueData.potentialCustomersId = this.rowData.customerId;
        this.ordeDetails()
      }else if (this.type === 'add') {
        // 其它模块进来
        console.log('其它模块进来:add', this.rowData)
        if (!this.rowData['potentialCustomersId'] && this.rowData['potentialCustomerId']) {
          this.rowData['potentialCustomersId'] = this.rowData['potentialCustomerId']
        }
        if (JSON.stringify(this.rowData!='{}')) {
          // 潜客跟进: 'potentialCustomerId'（潜客id）; 潜客管理: 'potentialCustomersId'（潜客id）
          // 因为潜客管理来的数据没有'potentialCustomerId'，故可以这么写。
          // 这里要保证潜客跟进来的数据一定要有potentialCustomerId，不然用了后面的商机id(潜客跟进)
          this.clueData.potentialCustomersId = this.rowData['potentialCustomerId'] || this.rowData['potentialCustomersId'];
          this.formList.forEach(x => {
            if(x.fieldName === 'consultant'){ // 特别处理
              x.initialValue = this.rowData['consultantName']
              this.EditConsultantId = this.rowData['consultant'] || null
            } else if (x.fieldName === 'customerNo') {
              x.initialValue = this.rowData['potentialCustomerNo']
            } else if(x.fieldName === 'industryType'){
              x.initialValue = this.rowData['industry']
            } else if(x.fieldName === 'birthday'){
                console.log(this.rowData[x.fieldName],"生日")
                if(this.rowData[x.fieldName]){
                  x.initialValue = formatdate(new Date(parseInt(this.rowData[x.fieldName])), 1);
                }
            }else if(x.fieldName === 'payMode'){
                x.initialValue =Number(this.rowData['payMode'])
            } else {
              x.initialValue = this.rowData[x.fieldName] || x.initialValue;
            }
          });
        }
        //20191204处理回显
        if(this.rowData['ctCode']){
          this.formList.find(item => item.fieldName == 'ctCode').initialValue =Number(this.rowData['ctCode'])
        }
        if(this.rowData['vehicleUse']){
          this.formList.find(item => item.fieldName == 'vehicleUse').initialValue=Number(this.rowData['vehicleUse'])
        }

        // console.log('填表', this.formList, this.rowData.customerNo)
        this.formList.find(item => item.fieldName == 'customerName').disabled = true;
        this.formList.find(item => item.fieldName == 'mobilePhone').disabled = true;
        this.formList.find(item => item.fieldName == 'consultant').disabled = true;
      }
    },
    ordeDetails (res){  //根据父组件传递的ID获取详细数据并赋值
      quyOrders(this.recordId).then(res => {
        if(res.resultCode == 200){
        res.data.sheetCreateDate = this.preDateHandler(res.data.sheetCreateDate);
        this.formList.forEach(x => {
          if(x.fieldName === 'consultant'){ // 特别处理
            this.EditConsultantId = Number(res.data['consultant']) == res.data['consultant'] ? res.data['consultant'] : res.data['consultantId'];
            x.initialValue = res.data[x.fieldName];
          } else if (x.fieldName === 'urls') {
            let urls = res.data['urls']
            let urlsList = urls.map(item => {
              let origin = item.split('/');
              let fileName = origin[origin.length-1];
              return { name: fileName, url: item};
            });
            x.initialValue.push(...urlsList)
          } else {
            x.initialValue = res.data[x.fieldName];
          }

          if(x.fieldName === 'birthday'){
            if(res.data[x.fieldName]&&parseInt(res.data[x.fieldName])>0){
              x.initialValue = formatdate(new Date(parseInt(res.data[x.fieldName])), 1);
            }
          }
        });
          this.formList2.forEach(x => x.initialValue = res.data[x.fieldName]);
          this.dataSource = res.data.vehicleList;
          // 显示第一个数据的服务项目
          this.dataSource.forEach(item => {
            item['showService'] = false
          })
          this.dataSource[0]['showService'] = true
          this.serviceSource = this.dataSource[0]['serviceItem']
          // 计算服务项目费用
          this.amountAmount()
          this.orderInfo = res.data;
        }
      });
    },
    addHendler (){ //新增中的新增
      console.log('新增')
      // this.visible2 = true
      this.visibleMultiple = true
      this.handleType = '产品选择'
      this.modifyType = false
    },
    addServicePrograms () { // 新增服务项目
      this.dataSource.length > 0 ? this.visibleService = true : ''
    },
    deleteHendler (){ //新增中的批量删除
      this.selectedRows.map( x => {
        this.dataSource = this.dataSource.filter( item => item.$index !== x.$index)
      })
      this.dataSource.some(item => item['showService'] === true) ? '' : this.serviceSource = []
      this.amountAmount()
    },
    deleteServicePrograms () { // 服务项目的批量删除
      this.$refs.tableA.$refs.pageTable.EXECUTE_DELETE(this.selectedServiceRows)
      this.amountAmount()
    },
    amountAmount (){ //计算数量和价格
      let [orderSum,serviceSum,totalSum] = [0,0,0];
      let dataSourceLength = this.dataSource.length
      console.log(this.dataSource,"this.dataSource")
      for(let i = 0; i < dataSourceLength; i++){
        orderSum = parseInt(this.dataSource[i].vehiclePrice) + parseInt(orderSum)
        let serviceItemLength
        if(this.dataSource[i].serviceItem && this.dataSource[i].serviceItem.length){
          serviceItemLength = this.dataSource[i].serviceItem.length
        }
        for (let k = 0; k < serviceItemLength; k++) {
          serviceSum += (this.dataSource[i].serviceItem[k].actualSellPrice || 0)
        }
      }
      totalSum = orderSum + serviceSum
      // 购车数目
      this.formList2.find(item => item.fieldName === 'vehicleSum').initialValue = this.dataSource.length
      // 购车总金额
      this.formList2.find(item => item.fieldName === 'orderSum').initialValue = orderSum?orderSum:0
      // 服务项目总金额
      this.formList3.find(item => item.fieldName === 'serviceSum').initialValue = serviceSum
      // 客户订单总金额
      this.formList3.find(item => item.fieldName === 'totalSum').initialValue = totalSum?totalSum:0
    },
    closeDialogs (val, row){ //线索选择的关闭-选择
      this.visible3 = val;
      this.clueData = row[0];
      let saveData = row[0]
      this.formList.find(item => item.fieldName == 'customerNo').initialValue = saveData.potentialCustomerNo
      this.formList.find(item => item.fieldName == 'customerName').initialValue = saveData.customerName
      this.formList.find(item => item.fieldName == 'mobilePhone').initialValue = saveData.mobilePhone
      if(saveData.birthday&&parseInt(saveData.birthday)>0){
        this.formList.find(item => item.fieldName == 'birthday').initialValue = formatdate(new Date(parseInt(saveData.birthday)), 1);
      }
      this.formList.find(item => item.fieldName == 'industryType').initialValue = saveData.industry
      // 特别处理 展示值
      this.formList.find(item => item.fieldName == 'consultant').initialValue = saveData.consultant
      // 特别处理 提交值
      this.EditConsultantId = saveData.consultantId
      this.formList.find(item => item.fieldName == 'ctCode').initialValue = saveData.ctCode
      this.formList.find(item => item.fieldName == 'certificateNo').initialValue = saveData.certificateNo
      this.formList.find(item => item.fieldName == 'address').initialValue = saveData.address
      this.formList.find(item => item.fieldName == 'vehicleUse').initialValue = saveData.vehicularApplication
    },
    closeDialogs2 (val){ //线索选择的关闭-未选择
      this.visible3 = val;
    },
    openDriveCancel2 (){ //新增中的客户编号选择
      console.log('客户')
      this.visible3 = true;
    },
    modifyHandle (row){ // 销售单修改
      console.log('modifyHandle',row)
      this.visible4 = true;
      this.modifyIndex = row.$index
      // this.type === 'edit'
      this.handleType = this.type
      this.formData = row
    },
    vehicleHandle (row) { // 配车
      this.visibleConfirmCar = true
      console.log('vehicleHandle',row)
      this.formData = row
      this.modifyIndex = row.$index
      // console.log('修改')
      // this.visible2 = true
      // this.handleType = '产品选择'
      // this.modifyType = true
      // //TODO
      // this.modifyIndex = row.$index
    },
    detailedHandle (row){ // 服务项目查看
      console.log('服务项目查看',row)
      // 切换前存数据
      try{
        // TODO:点地保存可能需要重复此操作
        this.dataSource.find(item => item['showService'] === true)['serviceItem'] = JSON.parse(JSON.stringify(this.serviceSource))
      } catch (e){
      }
      this.dataSource.forEach(item => {
        item['showService'] = false
      })
      this.dataSource[row.$index]['showService'] = true
      console.log(this.dataSource[row.$index]['serviceItem'])
      // 表单重现数据step.1
      this.serviceSource = this.dataSource[row.$index]['serviceItem']
      // 表单重现数据step.2可有可无
      // this.$refs.tableA.$refs.pageTable.EXECUTE_INSERT(this.dataSource[row.$index]['serviceItem'])
    },
    deleteHandle (row){ //单项删除
      this.dataSource = this.dataSource.filter( item => item.$index !== row.$index)
      let hasShowService = this.dataSource.some(item => item.showService == true)
      // hasShowService: true 当前展示数据还在;false当前展示数据本应该不在
      if (!hasShowService) {
        this.serviceSource = []
      }
      this.amountAmount()
    },
    deleteSingleService (row) { // 服务项目的单个删除
      this.$refs.tableA.$refs.pageTable.EXECUTE_DELETE([row])
      this.amountAmount()
    },
    selectChange (rows){ //选中时触发的函数
      console.log(rows)
      this.selectedRows = rows;
      this.isChoice = this.selectedRows.length > 0? false: true;
    },
    selectServiceChange (rows) { //选中时触发的函数
      console.log(rows)
      this.selectedServiceRows = rows;
      this.isServiceChoice = this.selectedServiceRows.length > 0? false: true;
    },
    formatDates: function(value) {
      // 这里的 value 就是需要过滤的数据
      if (value == null || value == "") {
        return "";
      }
      var date = new Date(Number(value));
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      return year + "-" + month + "-" + day;
    },
    createFormList() { //上方明细数据
      console.log('createFormList',this.type)
      return [
        {
          type: 'INPUT',
          label: '客户订单号',
          fieldName: 'soNo',
          placeholder: '',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '客户编号',
          fieldName: 'customerNo',
          placeholder: '请选择...',
          rules: [{ required: true, message: '请选择', trigger: 'blur'}],
          readonly: 'readonly',
          disabled: this.type === 'edit' || this.type === 'show' ? true : false,
          unitRender: () => {
	        	return <el-button slot="append" icon="el-icon-search" onClick={this.openDriveCancel2}></el-button>;
	        },
        },
        {
          type: 'SELECT',
          label: '订单状态',
          disabled: false,
          fieldName: 'soStatus',
          placeholder: '请选择...',
          disabled: true,
          initialValue: 14041001,
          itemList: this.createDictList('1404'),
        },
        {
          type: 'INPUT',
          label: '客户名称',
          fieldName: 'customerName',
          placeholder: '',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '手机号码',
          fieldName: 'mobilePhone',
          placeholder: '',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '销售顾问',
          fieldName: 'consultant',
          placeholder: '', // TODO:当前登录账号
          disabled: true,
          // initialValue: this.rowData.consultantId,
          // itemList: [],
        },
        {
          type: 'SELECT',
          label: '证件类型',
          fieldName: 'ctCode',
          placeholder: '请选择',
          initialValue: '',
          itemList: this.createDictList('1508'), // 原'1058'修改为'7035'再改'1508'
          rules: [{ required: true, message: '证件号码', trigger: 'change' }],
          change: val => {
            console.log(val)
            /*20191204关闭
            if(val==15081001){  //身份证
              this.formList.find(item => item.fieldName ==='certificateNo').rules=[{ required: false, trigger: 'blur', validator: IDNumber }]
            } else {
              this.formList.find(item => item.fieldName ==='certificateNo').rules=[]
            } */
          }
        },
        {
          type: 'INPUT',
          label: '证件号码',
          fieldName: 'certificateNo',
          placeholder: '',
          rules: [{ required: true, message: '证件号码', trigger: 'blur' }]
        },
        {
          type: 'DATE',
          label: '生日',
          fieldName: 'birthday',
          dateType: 'exactdate',
          // format: 'yyyy-MM-DD HH:mm',
          placeholder: '请选择',
          rules: [{ required: true, message: '请选择生日', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '联系地址',
          fieldName: 'address',
          placeholder: '',
          selfCols: 2,
          rules: [{ required: true, message: '请选择联系地址', trigger: 'blur' }]
        },
        {
          type: 'SELECT',
          label: '行业类型',
          fieldName: 'industryType',
          placeholder: '请选择...',
          itemList: this.createDictList('7030'),
          rules: [{ required: true, message: '请选择行业类型', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '开单日期',
          fieldName: 'sheetCreateDate',
          placeholder: '',
          disabled: true,
          initialValue: this.preDateHandler(new Date()),
        },
        {
          type: 'SELECT',
          label: '支付方式',
          fieldName: 'payMode',
          placeholder: '请选择...',
          initialValue: 14261001,
          itemList: this.createDictList('1426'),
        },
        {
          type: 'SELECT',
          label: '开票方式',
          fieldName: 'invoiceMode',
          placeholder: '请选择...',
          initialValue: 14291001,
          itemList: this.createDictList('1429'),
        },
        {
          type: this.type === 'add'?'SELECT':'INPUT',
          label: '开单人',
          fieldName: 'sheetCreatedBy',
          placeholder: '',
          disabled: true,
          initialValue: '',
          itemList: [],
        },
        {
          type: 'SELECT',
          label: '交车方式',
          fieldName: 'deliveryMode',
          placeholder: '请选择...',
          initialValue: 14281001,
          itemList: this.createDictList('1428'),
        },
        {
          type: 'SELECT',
          label: '车辆用途',
          fieldName: 'vehicleUse',
          placeholder: '请选择...',
          initialValue: '',
          itemList: this.createDictList('1511'),
          rules: [{ required: true, message: '请选择车辆用途', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '合同编号',
          disabled: false,
          fieldName: 'contractNo',
          placeholder: '',
          rules: [{ pattern: /^[a-zA-Z0-9]+$/, message: '请输入字母或数字', trigger: 'blur' }],
        },
        {
          type: 'INPUT_NUMBER',
          label: '合同定金',
          disabled: false,
          fieldName: 'contractEarnest',
          placeholder: '',
          rules: [{ pattern: /^(\d{1,8})?(\d{1,8}\.\d{1,2})?$/, message: '请输入1~8位整数，最多可有2位小数', trigger: 'blur' }],
        },
        {
          type: 'TEXT_AREA',
          label: '备注',
          fieldName: 'remark',
          selfCols: 2,
          maxlength: 32,
          placeholder: '',
        },
        {
          type: 'UPLOAD_FILE',
          label: '上传文件',
          fieldName: 'urls',
          selfCols: 3,
          placeholder: '上传文件...',
          style: {width: '300px'},
          upload: {
            actionUrl: '/api/file/oss/upload',
            limit: 4,
            tipText: '最多上传4个附件'
          }
        }
      ];
    },
    createFormList2 (){ //底部数据
      return [
        {
          type: 'INPUT',
          label: '购车总数量',
          fieldName: 'vehicleSum',
          disabled: true,
          placeholder: '',
          initialValue: 0,
        },
        {
          type: 'INPUT',
          label: '购车总金额',
          fieldName: 'orderSum',
          disabled: true,
          placeholder: '',
          initialValue: 0,
        }
      ]
    },
    createFormList3 () { //底部数据服务总价
      return [
        {
          type: 'INPUT',
          label: '服务项目总金额',
          fieldName: 'serviceSum',
          disabled: true,
          labelWidth:'150',
          style: {'display':'block','width': 'auto','margin-left':'100px'},
          placeholder: '',
          initialValue: 0,
        },
        {
          type: 'INPUT',
          label: '客户订单总金额',
          fieldName: 'totalSum',
          disabled: true,
          labelWidth:'150',
          style: {'display':'block','width': 'auto','margin-left':'100px'},
          placeholder: '',
          initialValue: 0,
        }
      ]
    },
    createTableColumns (){ //表格数据
      const _this = this
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 200,
          fixed: 'left',
          render: (props, h) => {
            let operateList = []
            let detailBtn = <el-button size="mini" disabled={props.row['showService']} type="text" onClick={props.row['showService']?'':() => this.detailedHandle(props.row)}>
                            服务
                          </el-button>
            let deleteBtn = <el-button size="mini" type="text" onClick={() => this.deleteHandle(props.row)}>
                            删除
                          </el-button>
            let modifyBtn = <el-button size="mini" type="text" onClick={() => this.modifyHandle(props.row)}>
                            修改
                          </el-button>
            let showBtn = <el-button size="mini" type="text" onClick={() => this.modifyHandle(props.row)}>
                            明细
                          </el-button>
            let vehicleBtn = <el-button size="mini" type="text" onClick={() => this.vehicleHandle(props.row)}>
                            配车
                          </el-button>
            let verticalElement = <el-divider direction="vertical" />
            if(this.type == 'show'){
              operateList = [
                detailBtn, verticalElement,
                showBtn
              ]
            } else {
              operateList = [
                deleteBtn, verticalElement,
                detailBtn, verticalElement,
                modifyBtn, verticalElement,
                vehicleBtn
              ]
            }
            return (<div>{operateList}</div>);
          }
        },
        {
	        title: '序号',
	        dataIndex: 'index',
	        width: 80,
	        render: props => {
	          return <span>{props.row.index + 1}</span>;
	        }
	      },
	      {
	        title: '销售订单号',
          dataIndex: 'viNo',
          width: 150,
          showOverflowTooltip:true,
	        filterType: 'input',
	      },
	      {
	        title: 'VIN',
          dataIndex: 'salesVin',
          showOverflowTooltip:true,
	        filterType: 'input',
	      },
	      // {
	      //   title: '开票名称',
	      //   dataIndex: 'customerName',
	      //   filterType: 'input',
        //   editable: this.type === 'add' ||  this.type === 'edit',
	      // },
	      // {
	      //   title: '开票联系人',
	      //   dataIndex: 'invoiceLinkMan',
	      //   filterType: 'input',
        //   // editable: this.type === 'add' ||  this.type === 'edit',
	      // },
	      // {
	      //   title: '开票电话',
	      //   dataIndex: 'invoiceMobile',
	      //   filterType: 'input',
        //   // editable: this.type === 'add' ||  this.type === 'edit',
	      // },
	      // {
	      //   title: '开票地址',
	      //   dataIndex: 'address', // invoiceAddress => address
	      //   filterType: 'input',
        //   // editable: this.type === 'add' ||  this.type === 'edit',
	      // },
	      {
	        title: '产品代码',
          dataIndex: 'productCode',
          showOverflowTooltip:true,
          width: 235,
	        filterType: 'input',
	      },
	      {
	        title: '品牌',
          dataIndex: 'brandName',
          showOverflowTooltip:true,
	        filterType: 'input',
	      },
	      {
	        title: '车系',
          dataIndex: 'seriesName',
          showOverflowTooltip:true,
	        filterType: 'input',
	      },
	      {
	        title: '车型',
          dataIndex: 'modelName',
          showOverflowTooltip:true,
	        filterType: 'input',
	      },
	      {
	        title: '配置',
          dataIndex: 'packageName',
          showOverflowTooltip:true,
          width: 230,
	        filterType: 'input',
	      },
	      {
	        title: '颜色',
          dataIndex: 'color',
          width: 115,
          showOverflowTooltip:true,
	        filterType: 'input',
	      },
	      {
	        title: '预交车日期',
          dataIndex: 'deliveringDate',
          width: 200,
          filterType: 'input',
          editable: false,
          showOverflowTooltip:true,
          render: function(props) {
            props.row.deliveringDate = Number(props.row.deliveringDate)
            let defaultTime = new Date().getTime()
            return (<div><el-date-picker
                    value = { props.row.deliveringDate }
                    disabled={ _this.type !== 'add' && _this.type !== 'edit'}
                    editable={false}
                    defaultValue={defaultTime}
                    onInput={(e)=>{
                      props.row.deliveringDate = new Date(e).getTime()
                    }}
                    type="date"
                    placeholder="选择日期">
                  </el-date-picker></div>)
          }
	      },
	      {
	        title: '销售单价',
	        dataIndex: 'vehiclePrice',
	        filterType: 'input',
          editable: true,
          render: props => { // Number(e)有点问题，小数点问题
            return <el-input disabled={ this.type !== 'add' &&  this.type !== 'edit'} value={props.row.vehiclePrice} placeholder="" onInput={(e)=>{
              props.row.vehiclePrice = Number(e) || 0;
              this.amountAmount();
            }}></el-input>
          }
	      },
	      {
	        title: '配车状态',
	        dataIndex: 'dispatchedStatus',
	        filterType: 'input',
          filterItems: this.createDictList('1414'),
          render: props => {
            return <span>{this.createDictText(props.row.dispatchedStatus, '1414')}</span>;
          }
	      }
      ]
    },
    createTableColumnsA () {
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 90,
          fixed: 'left',
          render: (props, h) => {
            if(this.type != 'show'){
              return (
                <div>
                  <el-button size="mini" type="text" onClick={() => this.deleteSingleService(props.row)}>
                    删除
                  </el-button>
                </div>
              );
            }
          }
        },
        {
	        title: '序号',
	        dataIndex: 'index',
	        width: 80,
	        render: props => {
	          return <span>{props.row.index + 1}</span>;
	        }
        },
	      {
	        title: '项目代码',
          dataIndex: 'serviceCode',
          showOverflowTooltip:true,
	        filterType: 'input',
	      },
	      {
	        title: '项目名称',
          dataIndex: 'serviceName',
          showOverflowTooltip:true,
	        filterType: 'input',
	      },
	      {
	        title: '费用类型',
          dataIndex: 'serviceType',
	        filterType: 'input',
          filterItems: this.createDictList('1421'),
          render: props => {
            return <span> { this.preDictHandler(props.row.serviceType,'1421')} </span>
          }
	      },
	      {
	        title: '费用金额',
          dataIndex: 'actualSellPrice',
	        filterType: 'input',
	      },
      ]
    },
    formChangeHandle(val) {
      this.saveData = _.cloneDeep(val);
    },
    formChangeHandle2(val) {
      console.log('formChangeHandle2', val)
      this.saveData2 = _.cloneDeep(val);
    },
    formChangeHandle3(val){
      console.log('formChangeHandle3', val)
      this.saveData3 = _.cloneDeep(val);
    },
    showHandler() {
      this.dialogTitle = `${this.conf[this.handleType]}`;
      this.visible = true;
    },
    // async subDialog (){ //订单提交
    //   console.log('提交')
    // },
    async saveDialog(isSubmit) { //订单保存
      this.$refs.formPanel.SUBMIT_FORM();
      // console.log(this.saveData)
      if(this.saveData !== null){
        if(this.dataSource.length == 0){
          this.$message({
            showClose: true,
            message: '请选择车辆产品',
            type: 'warning'
          });
          return
        }
        console.log('formList', this.formList)
        let orderData = this.formList //上方数据
        let orderData2 = this.formList2 //下方数据
        let orderData3 = this.columns //表格数据
        // 产品数量信息
        let productQuantityInfo = [];
        // let noOkayList = this.dataSource.filter(item => item['customerId'] == null || item['customerId'] == '' || item['customerId'] == undefined)
        // console.log('noOkayList',noOkayList)
        // if (noOkayList.length>0) {
        //   let listNo = noOkayList.map(item => item.$index+1)
        //   this.$message.error(`请为车辆序号${listNo.join(',')}配置客户信息`)
        //   return
        // }
        this.dataSource.forEach( (item, index) => {
          console.log("this.serviceSource",item)
          productQuantityInfo[index] = {
            provinceId:item.provinceId,
            saleType:item.saleType,
            cityId:item.cityId,
            districtId:item.districtId,
            brandId: item.brandId,
            deliveringDate: new Date(Number(item.deliveringDate)).getTime()?new Date(Number(item.deliveringDate)).getTime():"", //预交车日期
            // invoiceAddress: item.invoiceAddress, //开票地址
            // address: item['address'],	// TODO:联系地址/开票地址(address/adderss)
            // invoiceLinkMan: item.invoiceLinkMan, //开票联系人
            // invoiceMobile: item.invoiceMobile, //开票电话
            // invoiceName: item.invoiceName, //开票名称
            modelId: item.modelId, //车型Id
            packageId: item.packageId, //配置Id
            price: item.oemDirectivePrice, //价格销售指导价
            productId: item.productId, //产品ID不能为空
            seriesId: item.seriesId, //车系Id
            vehiclePrice: item.vehiclePrice, //车辆价格
            soNoId: this.recordId || '',
            viNo:  item['viNo'] || '',
            remark: item['remark'] || '',
            vin: item['salesVin'],
            vsStockId: item['vsStockId'],
            customerId: item['customerId'],
            customerType: item['customerType'], //客户类型
            // invoiceMobile: item['phone'], // 开票电话
            ctCode: item['ctCode'], // 证件类型
            certificateNo: item['certificateNo'], // 证件号码
            // invoiceLinkMan// 开票联系人
            // invoiceLinkManPhone // 开票联系人手机
            gender: item['gender'], // 性别
            birthday: item['birthday'] ? new Date(item['birthday']).getTime() : '', // 生日
            // address: item['adderss'],	// TODO:联系地址(address/adderss)
            industryType: item['industry'], // 行业类型
            serviceItem: item['serviceItem'],
          }
        })
        let certificateNo = orderData.find(item => item.fieldName == 'certificateNo').initialValue
        let consultant = orderData.find(item => item.fieldName == 'consultant').initialValue
        let contractEarnest = orderData.find(item => item.fieldName == 'contractEarnest').initialValue
        let contractNo = orderData.find(item => item.fieldName == 'contractNo').initialValue
        let ctCode = orderData.find(item => item.fieldName == 'ctCode').initialValue
        let deliveryMode = orderData.find(item => item.fieldName == 'deliveryMode').initialValue
        let invoiceMode = orderData.find(item => item.fieldName == 'invoiceMode').initialValue
        let payMode = orderData.find(item => item.fieldName == 'payMode').initialValue
        let address = orderData.find(item => item.fieldName == 'address').initialValue || null
        let remark = orderData.find(item => item.fieldName == 'remark').initialValue
        let vehicleUse = orderData.find(item => item.fieldName == 'vehicleUse').initialValue
        let soNo = orderData.find(item => item.fieldName == 'soNo').initialValue
        let birthday = orderData.find(item => item.fieldName == 'birthday').initialValue
        birthday = birthday.replace(/-/g,'/');
        let industryType = orderData.find(item => item.fieldName == 'industryType').initialValue
        let urls = orderData.find(item => item.fieldName == 'urls').initialValue
        let para = {
          certificateNo: certificateNo,
          consultant: Number(consultant) == consultant ? consultant : this.EditConsultantId,
          contractEarnest: contractEarnest,
          contractNo: contractNo,
          ctCode: ctCode,
          customerId: this.clueData.potentialCustomersId,
          deliveryMode: deliveryMode,
          birthday: new Date(birthday).getTime(),
          industryType: industryType,
          invoiceMode: invoiceMode,
          isSubmit: isSubmit, // 是否提交(点击提交按钮传10041001,点击保存传10041002)–APP/PC
          payMode:  payMode,
          address: address,
          //recordVersion: 0, // 版本号(修改时要传)–APP/PC
          remark: remark,
          vehicleUse: vehicleUse,
          salesOrderAppList: productQuantityInfo,
          soNo: soNo,
          soNoId: this.recordId || '',
          urls: urls?urls.map(x => x.url) : [], // 这里只接收url,不接收数据对象
        };
        console.log(para)
        let res = ''
        if (this.type == 'edit') {
          para.recordVersion = this.orderInfo.recordVersion
          res = await modifyOrders(para)
        } else {
          res = await addOrders(para)
        }
        if (res.resultCode === 200) {
          this.closeDialog('refresh');
        }
      }
    },
    closeDialog(param) {
      this.$emit('close', false, param);
    },
    resetFormList(data) {

    },
    closeHandler(val, data) {
      this.visible = val;
      if (!data) return;
      this.resetFormList(data);
    },
    //20191207Multiple
    closeHandler2Multiple(val, data) { //新增产品选择
      this.visibleMultiple = val;
      this.vehicleProductData = data;
      let productData = data;
      console.log(productData,"新增产品选择多选")
      let newDataArr = []
      productData.forEach((x,k)=>{
        for(let i = 0; i < productData[k].orderNumber1; i++){
          let newData = {
            // index: this.dataSource.length,
            brandId: productData[k]['brandId'],
            soNoId: this.recordId || '',
            viNo: '',
            salesVin: '',
            remark: '',
            invoiceName: productData[k]['invoiceName'],
            // invoiceLinkMan: productData.co,
            // invoiceMobile: productData.invoiceMobile,
            // invoiceAddress: productData.invoiceAddress,
            productCode: productData[k]['productCode'],
            brandName: productData[k]['brandName'],
            seriesName: productData[k]['seriesName'],
            modelName: productData[k]['modelName'],
            packageName: productData[k]['packageName'],
            color: productData[k]['color'],
            deliveringDate:  new Date().getTime(),
            vehiclePrice: productData[k]['vehiclePrice'] || productData[k]['oemDirectivePrice'] || 0,
            dispatchedStatus: 14141001, // 未配车
            modelId: productData[k]['modelId'], //车型Id
            packageId: productData[k]['packageId'], //配置Id
            price: productData[k]['oemDirectivePrice'], //价格销售指导价
            productId: productData[k]['productId'], //产品ID不能为空
            productName: productData[k]['productName'], // 产品名称
            seriesId: productData[k]['seriesId'], //车系Id
            showService: false, // 服务按钮状态
            serviceItem: []
          }
          console.log(k,newData)
          newDataArr.push(newData)
      }
      })
      console.log(newDataArr,"newDataArr")
      // TODO:
      this.$refs.table.$refs.pageTable.EXECUTE_INSERT(newDataArr)
      // 新增时第一个数据默认 添加服务项目
      if(this.dataSource&&this.dataSource.length>0&&!this.dataSource.some(item => item.showService)){
        this.dataSource[0]['showService'] = true
        this.serviceSource = this.dataSource[0]['serviceItem']
      }
      this.amountAmount()
    },
    //20191207Multiple
    closeHandler22Multiple (val){
      this.visibleMultiple = val;
      this.modifyIndex = null
    },
    closeHandler2(val, data) { //新增产品选择
      this.visible2 = val;
      this.vehicleProductData = data[0];
      let productData = data[0];
      console.log(productData)
      let _index = this.modifyIndex
      this.modifyIndex = null
        // "salesOederDetailId": 0,
      if (_index !== null) {
        let newProduct = {
          // index: _index,
          brandId: productData.brandId,
          viNo: this.dataSource[_index].viNo,
          soNoId: this.recordId || '',
          salesVin: '',
          remark: '',
          invoiceName: productData.invoiceName,
          // invoiceLinkMan: productData.invoiceLinkMan,
          // invoiceMobile: productData.invoiceMobile,
          // invoiceAddress: productData.invoiceAddress,
          productCode: productData.productCode,
          brandName: productData.brandName,
          seriesName: productData.seriesName,
          modelName: productData.modelName,
          packageName: productData.packageName,
          color: productData.color,
          deliveringDate: new Date().getTime(),
          vehiclePrice: productData.vehiclePrice || productData.oemDirectivePrice || 0,
          dispatchedStatus: 14141001, // 未配车
          modelId: productData.modelId, //车型Id
          packageId: productData.packageId, //配置Id
          price: productData.oemDirectivePrice, //价格销售指导价
          productId: productData.productId, //产品ID不能为空
          productName: productData.productName, // 产品名称
          seriesId: productData.seriesId, //车系Id
          showService: this.dataSource[_index].showService,
          serviceItem: this.dataSource[_index].serviceItem,
        }
        this.dataSource.splice(_index, 1, newProduct)
      } else {
        for(let i = 0; i < productData.orderNumber1; i++){
          // delete productData._uid
          // productData.index = this.dataSource.length
          let newData = {
            // index: this.dataSource.length,
            brandId: productData.brandId,
            soNoId: this.recordId || '',
            viNo: '',
            salesVin: '',
            remark: '',
            invoiceName: productData.invoiceName,
            // invoiceLinkMan: productData.co,
            // invoiceMobile: productData.invoiceMobile,
            // invoiceAddress: productData.invoiceAddress,
            productCode: productData.productCode,
            brandName: productData.brandName,
            seriesName: productData.seriesName,
            modelName: productData.modelName,
            packageName: productData.packageName,
            color: productData.color,
            deliveringDate: new Date().getTime(),
            vehiclePrice: productData.vehiclePrice || productData.oemDirectivePrice || 0,
            dispatchedStatus: 14141001, // 未配车
            modelId: productData.modelId, //车型Id
            packageId: productData.packageId, //配置Id
            price: productData.oemDirectivePrice, //价格销售指导价
            productId: productData.productId, //产品ID不能为空
            productName: productData.productName, // 产品名称
            seriesId: productData.seriesId, //车系Id
            showService: false, // 服务按钮状态
            serviceItem: []
          }
          // TODO:
          this.$refs.table.$refs.pageTable.EXECUTE_INSERT(newData)
        }
      }
      // 新增时第一个数据默认 添加服务项目
      if(this.dataSource&&this.dataSource.length>0&&!this.dataSource.some(item => item.showService)){
        this.dataSource[0]['showService'] = true
        this.serviceSource = this.dataSource[0]['serviceItem']
      }
      this.amountAmount()
    },
    closeHandler22 (val){
      this.visible2 = val;
      this.modifyIndex = null
    },
    closeServiceDialog(val=false,data){ // 服务项目dialog关闭
      this.visibleService = false
      console.log('closeServiceDialog',data)
      // 有新增数据
      if (data && data.length > 0) {
        this.$refs.tableA.$refs.pageTable.EXECUTE_INSERT(data)
        console.log('closeServiceDialog',this.serviceSource)
        // this.dataSource.find(x => x.showService === true)['serviceItem'] = JSON.parse(JSON.stringify(this.serviceSource))
      }
      this.amountAmount()
    },
    closeConfirmCar (isOpen = false, val) { // 配车dialog关闭
      let { modifyIndex } = this
      console.log('closeConfirmCar', modifyIndex, val)
      this.visibleConfirmCar = false
      if (val && val.length > 0) {
        // 有新增数据
        this.dataSource[modifyIndex]['salesVin'] = val[0].vin
        this.dataSource[modifyIndex]['vsStockId'] = val[0].vsStockId
        // this.dataSource.find(x => x.showService === true)['serviceItem'].push(...val)
      }
      this.modifyIndex = null
    },
    closeHandler4(val, data) {//销售单明细
      let { modifyIndex } = this
      this.visible4 = val;
      if (data) {
        for (let item in data) {
          // dataSource[modifyIndex]有的数据重新赋值,没有的数据添加数据
          this.dataSource[modifyIndex][item] = data[item]
        }
        // 修改数据
        this.dataSource.splice(modifyIndex, 1, this.dataSource[modifyIndex])
      }
      console.log(this.dataSource)
      // 强制数据重新渲染
      this.dataSource.findIndex(item => item['showService'] === true) === modifyIndex ?
      this.serviceSource = JSON.parse(JSON.stringify(this.dataSource[modifyIndex]['serviceItem'])) : ''
      this.modifyIndex = null
      this.amountAmount()
    },
    async openDriveCancel() {
      this.handleType = 'search';
      this.visible = true;
      this.showHandler();
    },
    // 字典数据使用前预处理
    preDictHandler(val, code){
      let resultText = val && String.prototype.includes.call(val, code) ? this.createDictText(val, code) : val;
      return resultText;
    },
    // 日期预处理
    preDateHandler(val, formatCode='YYYY-MM-DD HH:mm:ss') {
      let resultDate = val ? moment(Number(val)).format(formatCode) : val;
      if ((resultDate == 'Invalid date' || resultDate == 'Invalid Date') && val) {
        resultDate = moment(val).format(formatCode)
      }
      return resultDate;
    },
  }
};
</script>

<style lang="less" scoped>
</style>

